import { Effect, Reducer, Subscription } from 'umi';
import { getAppsList } from '../services/apps'

export interface AppsState {
  appList: {
    name: string,
    to: string,
    entry: string,
    props: {
      description: string
    }
  }[]
}

export interface AppsModelType {
  namespace: 'Apps';
  state: AppsState;
  effects: {
    getApps: Effect;
  };
  reducers: {
    save: Reducer<AppsState>;
  };
  subscriptions: { setup: Subscription };
}

const AppsModel: AppsModelType = {
  namespace: 'Apps',
  state: {
    appList: []
  },

  effects: {
    *getApps({ payload }, { call, put }) {
      const apps = yield call(getAppsList)
      yield put(
        {
          type: 'save',
          payload: apps
        }
      )
    },
  },
  reducers: {
    save(state, { payload }) {
      let appList = payload
      return { appList }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/workplace') {
          dispatch({
            type: 'getApps',
          });
        }
      });
    },
  },
};

export default AppsModel;